function [QW,Copula]=DistApp_Hist_MarginCopulaF2QW(MarginQWCell,CopulaF,FormatFlag)


%% Preliminaries
% 1. Dimension Information, Remove the Degenerated Quardrature Points
N_Dim       =   length(MarginQWCell);
if N_Dim~=length(CopulaF.GridVectors)
    error('Dimension is Inconsistent');
end
UnitNumList =   zeros(1,N_Dim);
NzIndCell   =   cell(N_Dim,1);
NzNumList   =   zeros(1,N_Dim);
MarginCDF   =   cell(1,N_Dim);
for ii=1:N_Dim
    UnitNumList(ii) =   length(MarginQWCell{ii});
    TempNzIdx       =   abs(MarginQWCell{ii})>eps;
    NzNumList(ii)   =   sum(TempNzIdx);
    NzIndCell{ii}   =   find(TempNzIdx);
    MarginCDF{ii}   =   cumsum(MarginQWCell{ii}(TempNzIdx));
end
% 2. Compute the Distribution
Copula      =   CopulaF(MarginCDF);
CDF_Mat     =   reshape(Copula,NzNumList);
NzQW_Mat    =   CDF_Mat;
IdxCell     =   cell(1,N_Dim);
for ii=1:N_Dim
    IdxCell{ii}     =   (1:1:NzNumList(ii))';
end
for ii=1:N_Dim
    if NzNumList(ii)>1
        TempIdxCell     =   IdxCell;
        TempIdxCell{ii} =   (2:1:NzNumList(ii))';
        NzQW_Mat(TempIdxCell{:}) ...
                        =   diff(NzQW_Mat,1,ii);
    end
end

% 3. Recover the Original Matrix Shape
QW_Mat      =   zeros(UnitNumList);
QW_Mat(NzIndCell{:}) ...
            =   NzQW_Mat;
QW_Vec      =   max(QW_Mat(:),0);
QW_Vec      =   QW_Vec/sum(QW_Vec);

if nargin<=2
    FormatFlag  =   'Vector';
end
switch FormatFlag
    case 'Vector'
        QW      =   QW_Vec;
    case 'Matrix'
        QW      =   reshape(QW_Vec,UnitNumList(:));
end
